<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/31
 * Time: 11:47
 */

namespace App\Http\Controllers\Api\V1;


use App\Models\Coach;
use App\Models\Comment;
use App\Models\Period;
use App\Models\PutPeriod;
use App\Models\School;
use App\Models\Student;
use App\Models\CoachConfig;
use App\Models\StudentScore;
use App\Models\Subscribe;
use App\Models\User;
use App\Models\Message;
use App\Models\StudentCount;
use App\Models\StudentCoach;
use App\Models\StudentState;
use App\Models\TcpStudytime;
use App\Repositories\CoachsRepository;
use App\Repositories\EvaluationRepository;
use App\Repositories\StudentRepository;
use App\Repositories\MessageRepository;
use App\Repositories\StudytimeRepository;
use App\Repositories\SubscribesRepository;
use App\Repositories\StudentCountRepository;
use App\Repositories\CommentsRepository;
use App\Repositories\StudentStateRepository;
use App\Repositories\OrderListRepository;
use App\Repositories\PutimesRepository;
use App\Repositories\TemplateRepository;
use App\Transformers\CoachDetailsTransformer;
use App\Transformers\EvaluationTransformer;
use App\Transformers\FeedbackTransformer;
use App\Transformers\MessageTransformer;
use App\Transformers\OperationTransformer;
use App\Transformers\PeriodCoachTransformer;
use App\Transformers\PeriodTransformer;
use App\Transformers\SubscribeTransformer;
use App\Transformers\MySubscribeTransformer;
use App\Transformers\PaymentDetailTransformer;
use App\Models\SchoolConfig;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Libs\Umeng;
use App\Transformers\UserTransformer;
use App\Repositories\ServiceRepository;

class CoachController extends BaseController
{
    protected $study;
    protected $coachs;
    protected $evaluation;
    protected $subscribe;
    protected $student;
    protected $message;
    protected $comments;
    protected $student_count;
    protected $student_state;
    protected $order_list;
    protected $period;
    protected $service;
    protected $putimes;
    protected $template;

    public function __construct(
        StudytimeRepository $studytimeRepository,
        CoachsRepository $coachsRepository,
        EvaluationRepository $evaluationRepository,
        SubscribesRepository $subscribesRepository,
        StudentRepository $studentRepository,
        MessageRepository $messageRepository,
        CommentsRepository $comments,
        StudentCountRepository $studentCount,
        StudentStateRepository $studentState,
        OrderListRepository $order_list,
        StudytimeRepository $period,
        ServiceRepository $service,
        PutimesRepository $putimesRepository,
        TemplateRepository $template
    )
    {
        $this->student = $studentRepository;
        $this->study = $studytimeRepository;
        $this->coachs = $coachsRepository;
        $this->evaluation = $evaluationRepository;
        $this->subscribe = $subscribesRepository;
        $this->message = $messageRepository;
        $this->comments = $comments;
        $this->student_count = $studentCount;
        $this->student_state = $studentState;
        $this->order_list = $order_list;
        $this->period = $period;
        $this->service = $service;
        $this->putimes = $putimesRepository;
        $this->template = $template;
    }


    /**
     * @api {get} /coach  教练首页
     * @apiDescription  教练首页
     * @apiGroup Coach
     * @apiSampleRequest /api/coach
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "取消成功!",
     *       "status_code": 200
     *   }
     */
    public function index(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $data['coach_name'] = $user->item->name;
        $data['photo'] = $user->item->photo;
        $data['period_info'] = PutPeriod::where('coach_id', $user->item_id)->where('startime', '>', time())->orderBy('startime', 'asc')->first();
        $data['period_count'] = Subscribe::leftJoin('yy_put_periods', 'yy_subscribes.putime_id', '=', 'yy_put_periods.id')
            ->where('yy_subscribes.coach_id', $user->item_id)
            ->where('yy_subscribes.status', '!=', 3)->sum('study_time');

        $comment_all = Comment::where('coach_id', $user->item_id)->count();
        $comment_perfect = Comment::where('comment', 2)->where('coach_id', $user->item_id)->count();
        $comment_good = Comment::where('comment', 1)->where('coach_id', $user->item_id)->count();

        $data['evaluationrate'] = $comment_all ? number_format(($comment_good + $comment_perfect) / $comment_all, 2) : 0;

        $school_config = SchoolConfig::where('school_id', $user->item->school_id)->first();
        $single_time = $school_config && $school_config->sch_putime_length ? $school_config->sch_putime_length : 60;
        $train_count = TcpStudytime::where('coachnum', $user->item->coachnum)->sum('duration');
        $data['train_count'] = number_format($train_count / $single_time);
        return $this->successResponse('success', ['data' => $data]);
    }

    /**
     * @api {get} /coach/periodList 教练预约学车信息(student studycar)
     * @apiDescription 教练预约学车信息
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/periodList
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {String} [date]  date
     * @apiParam {String} [km]  km
     * @apiParam {String} [startime]  startime
     * @apiParam {String} [endtime]  endtime
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *        "message": "success",
     * "code": 200,
     * "data": {
     * "schoolConfig": {
     * "id": 93,
     * "school_id": 36,
     * "issubscribe": 1,
     * "istheory": 0,
     * "sch_putime_length": 0,
     * "sch_putime_interval": 0,
     * "sch_putime_operation": 0,
     * "sch_vip1_univalence": "0.00",
     * "sch_vip2_univalence": "0.00",
     * "sch_vip3_univalence": "0.00",
     * "sch_vip4_univalence": "0.00",
     * "sch_vip5_univalence": "0.00",
     * "sch_sign": 0,
     * "sch_signtime": 0,
     * "putime_template": 1,
     * "orderputime": 0,
     * "quxiaoputime": 0,
     * "isshow_coachofstudentnum": 1,
     * "isshow_allputime": 0,
     * "isshow_allcoachputime": 0,
     * "slogan": "",
     * "putime_day": 3,
     * "recommend": 0,
     * "column": 1,
     * "ischeck": 2,
     * "student_login": 2,
     * "video_player_num": 0,
     * "self_motion_comment": 0,
     * "self_motion_comment_day": 0,
     * "unlimited_putime_max": 99,
     * "created_at": "2017-04-17 11:55:32",
     * "updated_at": "2017-04-17 11:57:02",
     * "open_recruit": 1
     * }
     * }
     *   }
     */
    public function periodList(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $param = [
            'date' => $request->get('date'),
            'km' => $request->get('km'),
            'startime' => strtotime($request->get('startime')),
            'endtime' => strtotime($request->get('endtime')),
            'coach_id' => $user->item_id,
        ];

        $lists = $this->study->coachPeriodList($param);

        return $this->successResponse('success', ['data' => $lists]);
    }


    /**
     * @api {post} /coach/deletePutime  删除未预约学时(coach deletePutime)
     * @apiDescription  删除未预约学时(coach deletePutime)
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/deletePutime
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [putime_id]  学时id
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "删除成功!",
     *       "status_code": 200
     *   }
     */
    public function deletePutime(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token
        $putime_id = $request->get('putime_id', 0);
        if (!$putime_id) {
            return $this->errorResponse('参数错误');
        }
        $status = $this->subscribe->deletePutime($putime_id);
        if ($status['status'] == -1) {
            return $this->errorResponse($status['message']);
        } else {
            return $this->successResponse('删除成功');
        }
    }

    /**
     * @api {post} /coach/cancelPutime  教练取消预约(coach cancelPutime)
     * @apiDescription  教练取消预约(coach cancelPutime)
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/cancelPutime
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [putime_id]  学时id
     * @apiParam {String} [student_id]  学员id
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "取消成功!",
     *       "status_code": 200
     *   }
     */
    public function cancelPutime(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token
        $putime_id = $request->get('putime_id', 0);
        $student_id = $request->get('student_id', 0);
        if (!$putime_id || !$student_id) {
            return $this->errorResponse('参数错误');
        }
        $status_info = $this->subscribe->deleAllPutime($putime_id, $student_id, 2,$user->item);
        $student_info = $this->student->getById($student_id);


        if ($status_info !== false) {

            if ($status_info->km == 2) {
                $km = '科二实操练习';
            } else {
                $km = '科三实操练习';
            }
            $msg['content'] = $status_info->coach->name .'教练为您取消了：' . date('Y-m-d H:i', $status_info->startime) . ' ~ ' . date('H:i', $status_info->endtime) . ' 的' . $km;
            $msg['from_type'] = 2;//消息来源教练
            $msg['from_id'] = $status_info->coach->id;
            $msg['to_type'] = 1;//消息接受学员
            $msg['to_id'] = $student_info->id;

            if ($student_info->device_type == 'ios') {
                $msg['device_type'] = 1;
            } elseif ($student_info->device_type == 'android') {
                $msg['device_type'] = 2;
            }

            $msg['created_at'] = date('Y-m-d H:i:s');
            Message::insert($msg);


            if ($student_info->device_token) {
                $umen = new Umeng($student_info->device_type, 3);
                $umen->sendNotificationToDevices(['title' => '预约取消提示', 'text' => $msg['content'], 'device_tokens' => $student_info->device_token]);
            }
            $msg['content'] = '您取消了' . $student_info->name . '学员：' . date('Y-m-d H:i', $status_info->startime) . ' ~ ' . date('H:i', $status_info->endtime) . ' 的' . $km;
            $msg['from_type'] = 2;//消息来源
            $msg['from_id'] = $user->item_id;
            $msg['to_type'] = 2;//消息接受教练
            $msg['to_id'] = $user->item_id;
            $msg['device_type'] = 3;
            Message::insert($msg);
            $coach_id = User::where('item_id', $status_info->coach->id)->where('item_type', 'App\Models\Coach')->value('id');
            $user_id = User::where('item_id', $student_info->id)->where('item_type', 'App\Models\Student')->value('id');
            $student_count = StudentCount::where('student_id',$student_info->id)->first();
            if (!empty($coach_id) || !empty($user_id)) {
                $data['km'] = $status_info->km;
                $data['status'] = 2;
                $data['userId'] = $user_id;
                $data['name'] = $student_info->name;
                $data['phone'] = $student_info->phone;
                $data['cocahUserId'] = $coach_id;
                $data['cocahName'] = $status_info->coach->name;
                $data['cocahPhone'] = $status_info->coach->mobile;
                $data['location'] = '';
                $data['return_hours'] = $status_info->study_time;
                $data['surplus_hours'] = $student_count->km2period + $student_count->km3period;
                $data['times'] = date('Y-m-d H:i', $status_info->startime) . ' ~ ' . date('H:i', $status_info->endtime);
                $data['userType'] = 2;
                $this->subscribe->post_weixin_student_yy($data);
            }
            return $this->successResponse('取消成功');
        } else {
            return $this->errorResponse($this->subscribe->error ? $this->subscribe->error : '操作失败');
        }
    }

    /**
     * @api {get} /coach/coachLeaveList 教练请假信息
     * @apiDescription 教练请假信息
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/coachLeaveList
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *        "message": "success",
     * "code": 200,
     * "data": [
     * {
     * "id": 11,
     * "item_id": 507,
     * "startime": "2017-10-18 09:00:00",
     * "endtime": "2017-10-18 10:00:00",
     * "content": "回家吃饭",
     * "isstate": 0,
     * "created_at": "-0001-11-30 00:00:00",
     * "type_id": 53
     * },
     * {
     * "id": 10,
     * "item_id": 507,
     * "startime": "2017-10-15 09:00:00",
     * "endtime": "2017-10-15 12:00:00",
     * "content": "",
     * "isstate": 1,
     * "created_at": "-0001-11-30 00:00:00",
     * "type_id": 53
     * },
     * {
     * "id": 9,
     * "item_id": 507,
     * "startime": "2017-10-14 09:00:00",
     * "endtime": "2017-10-14 11:00:00",
     * "content": "",
     * "isstate": 1,
     * "created_at": "-0001-11-30 00:00:00",
     * "type_id": 51
     * }
     * ]
     *   }
     */
    public function coachLeaveList(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token
        $lists = $this->coachs->getCoachLeave($user->item_id);
        return $this->successResponse('success', ['data' => $lists]);
    }


    /**
     * @api {post} /coach/coachLeave  教练请假(coach coachLeave)
     * @apiDescription  教练请假(coach coachLeave)
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/coachLeave
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {String} [content]  content
     * @apiParam {Number} [type_id]  type_id
     * @apiParam {String} [startime]  startime
     * @apiParam {String} [endtime]  endtime
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "请求成功!",
     *       "status_code": 200
     *   }
     */
    public function coachLeave(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        $school_coach_config = CoachConfig::where('school_id', $user->item->school_id)->where('type', 2)->first();

        if($school_coach_config && $school_coach_config['ch_leave'] != 1){
            return $this->errorResponse('没有请假的权限!');
        }

        $data['startime'] = $request->get('startime');
        $data['endtime'] = $request->get('endtime');
        $data['type_id'] = $request->get('type_id');
        $data['content'] = $request->get('content');
        $data['item_id'] = $user->item_id;
        $data['isstate'] = 3;
        $data['created_at'] = date('Y-m-d H:i:s');
        if (empty($data['startime']) || empty($data['endtime']) || empty($data['type_id'])) return $this->errorResponse('请填写完整信息');
        $startime = strtotime($data['startime']);
        $endtime = strtotime($data['endtime']);
        $putimeCount = $this->subscribe->getPutimeTotime($startime, $endtime, $user->item_id);
        if ($putimeCount > 0) return $this->errorResponse('该时段已有学时投放,不能请假!');
        $status = $this->coachs->addLeave($data);
        if ($status) {
            return $this->successResponse('请求成功!');
        } else {
            return $this->errorResponse('请假时间重复');
        }
    }

    /**
     * @api {get} /coach/myMessages 我的消息(coach messages)
     * @apiDescription 我的消息(coach messages)
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/myMessages
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [page]  1
     * @apiParam {Number} [size]  10
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function myMessages(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        /*if(!$this->checkCoachToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }*/

        $size = $request->get('size', 10);
        $param['to_id'] = $user->item_id;
        $param['to_type'] = 2;//发送给教练的消息
        $param['page'] = $request->get('page', 1);

        $lists = $this->message->index($param, '', $size);

        $data = [];
        $data['list'] = [];
        if (count($lists)) {

            $transformer = new MessageTransformer;

            foreach ($lists['list'] as $v) {
                if ($v->from_type == 1) {
                    $from_user = School::find($v->from_id);
                } else {
                    $from_user = Coach::find($v->from_id);
                }

                $v->fromuser = $from_user;

                $data['list'][] = $transformer->transform($v);
            }
        }
        $data['count'] = $lists['count'];

        return $this->successResponse('success', ['data' => $data]);
    }


    /**
     * @api {get} /coach/profile 教练个人资料
     * @apiDescription 教练个人资料
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/profile
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *        "message": "success",
     * "code": 200,
     * "data": {
     * "schoolConfig": {
     * "id": 93,
     * }
     * }
     *   }
     */
    public function profile(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $lists = $this->coachs->profile($user->item);

        return $this->successResponse('success', ['data' => $lists]);
    }


    /**
     * @api {get} /coach/mystudentzmlist 我的学员(coach mystudentzmlist)
     * @apiDescription 我的学员(coach mystudentzmlist)
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/mystudentzmlist
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [size]  10
     * @apiParam {Number} [page]  1
     * @apiParam {String} [keyword]
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *        "message": "success",
     * "code": 200,
     * "data": {
     * "schoolConfig": {
     * "id": 93,
     * }
     * }
     *   }
     */
    public function mystudentzmlist(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token
        $size = $request->input('size', 10);
        $page = $request->input('page', 1);
        $keyword = $request->input('keyword');
        $lists = $this->student->getAllToWhere(['coach_id' => $user->item_id, 'keyword' => $keyword], $size, $page);
        $school_config = SchoolConfig::where('school_id', $user->item->school_id)->first();
        $listzmlsit = [];
        foreach ($lists as $key => $val) {
            $putimes = $this->putimes->index(['userid' => $val['id'], 'type' => 1]);
            $val['sch_putime_length'] = $school_config && $school_config->sch_putime_length ? $school_config->sch_putime_length : 60;
            $val['put_time'] = $putimes ? $putimes['syllabus'] : [];
            $val['name'] = removeSpaces($val['name']);
            if (empty($val['id']) || empty($val['name']) || strpos(' ',$val['name']) == true) {
                unset($lists[$key]);
                continue;
            }
            $listzmlsit[] = $val;
        }
        return $this->successResponse('success', ['data' => $listzmlsit]);
    }

    /**
     * @api {get} /coach/myPutperiod 教练工时
     * @apiDescription 教练工时
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/myPutperiod
     * @apiPermission none
     * @apiParam {String} [type]  1,年度，2，月度
     * @apiParam {int} [page]  page
     * @apiParam {int} [size]  size
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function myPutperiod(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $type = $request->input('type');
        $page = $request->input('page', 1);
        $size = $request->input('size', 15);

        list($list, $total, $year_total, $month_total) = $this->subscribe->coachPeriod($user->item, $type);

        $data['list'] = $list;
        $data['total'] = $total;
        $data['year_total'] = $year_total;
        $data['month_total'] = $month_total;

        return $this->successResponse('success', ['data' => $data]);

    }


    /**
     * @api {get} /coach/myTrainRecords 教练培训工时
     * @apiDescription 教练培训工时
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/myTrainRecords
     * @apiPermission none
     * @apiParam {String} [type]  1,年度，2，月度
     * @apiParam {int} [page]  page
     * @apiParam {int} [size]  size
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function myTrainRecords(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $type = $request->input('type');
        $page = $request->input('page', 1);
        $size = $request->input('size', 15);

        list($list, $total, $year_total, $month_total) = $this->putimes->coachTrainRecords($user->item, $type, $page, $size);

        $school_config = SchoolConfig::where('school_id', $user->item->school_id)->first();
        $sch_putime_length = $school_config && $school_config->sch_putime_length ? $school_config->sch_putime_length : 60;

        $data['list'] = $list;
        $data['total'] = $total;
        $data['year_total'] = $year_total;
        $data['month_total'] = $month_total;
        $data['sch_putime_length'] = $sch_putime_length;

        return $this->successResponse('success', ['data' => $data]);
    }


    /**
     * @api {get} /coach/mystudentinfo 我的学员个人资料(coach mystudentinfo)
     * @apiDescription 我的学员个人资料(coach mystudentinfo)
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/mystudentinfo
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [student_id]  学员ID
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *        "message": "success",
     * "code": 200,
     * "data": {
     * "schoolConfig": {
     * "id": 93,
     * }
     * }
     *   }
     */
    public function mystudentinfo(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token
        $student_id = $request->get('student_id');
        $trans = new UserTransformer;
        $info = $this->student->getById($student_id);
        $service_info = $this->service->getByServiveInfo($info->service_id);
        $info->sstc = $service_info ? $service_info->subscribetype : '';
        $info->config = $service_info ? $service_info->config : '';//服务项目及权限;
        $info->student_count = $this->student_count->getByStudentInfo($student_id, $info->school_id);
        $info->syllaus_time = $this->putimes->getSyllausTime($student_id);
        $info->userId = $user->id;
        $student_info = Student::find($student_id);
        $info->subinfo = $this->student_count->getSubInfo($student_info);
        return $this->successResponse('success', ['data' => $trans->transform($info)]);
    }

    /**
     * @api {get} /coach/statelist 我的投诉(coach statelist)
     * @apiDescription 我的投诉(coach statelist)
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/statelist
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function statelist(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token
        $lists = $this->student_state->getByCoachIdList($user->item_id);
        return $this->successResponse('success', ['data' => $lists]);
    }

    /**
     * @api {post} /coach/commentsList 我的评价
     * @apiDescription 我的评价
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/commentsList
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {String} [keyword]  学员姓名筛选
     * @apiParam {String} [starttime]  开始时间
     * @apiParam {String} [endtime]  结束时间
     * @apiParam {Int} [page]  第几页
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function commentsList(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $params['keyword'] = $request->input('keyword');
        $params['starttime'] = $request->input('starttime');
        $params['endtime'] = $request->input('endtime');
        $page = $request->input('page', '1');
        $size = $request->input('size', '15');

        list($total, $list) = $this->comments->serachComments($user->item, $params, $page, $size);

        $data['total'] = $total;
        $data['list'] = $list;

        return $this->successResponse('success', ['data' => $data]);
    }


    /**
     * @api {get} /coach/myreport 我的报表
     * @apiDescription 我的报表
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/myreport
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function myreport(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $timestamp = time();
        $firstday = date('Y-m-01', strtotime(date('Y', $timestamp) . '-' . (date('m', $timestamp) - 1) . '-01'));
        $lastday = date('Y-m-d 23:59:59', strtotime("$firstday +1 month -1 day"));
        $last_month = array(strtotime($firstday), strtotime($lastday));
        $now_month = array(strtotime(date('Y-m-01')), strtotime(date('Y-m-t') . ' +1 day') - 1);

        $data['stu_count'] = StudentCoach::where('cid', $user->item_id)->count(DB::raw('distinct stuid'));

        $period_count = $this->period->coachPeriodCount($user->item);
        $data['putimecount'] = $period_count['puted'];
        $data['completecount'] = $period_count['subscribed'];

        $last_period_count = $this->period->coachPeriodCount($user->item, '', date('Y-m-d', $last_month[0]), date('Y-m-d H:i:s', $last_month[1]));
        $data['lastputimecount'] = $last_period_count['puted'];
        $data['lastcompletecount'] = $last_period_count['subscribed'];

        $now_period_count = $this->period->coachPeriodCount($user->item, '', date('Y-m-d', $now_month[0]), date('Y-m-d H:i:s', $now_month[1]));
        $data['nowputimecount'] = $now_period_count['puted'];
        $data['nowcompletecount'] = $now_period_count['subscribed'];

        $data['verygoodcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 2)->count();
        $data['lastverygoodcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 2)
            ->where('createtime', '>=', $last_month[0])
            ->where('createtime', '<=', $last_month[1])->count();
        $data['nowverygoodcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 2)
            ->where('createtime', '>=', $now_month[0])
            ->where('createtime', '<=', $now_month[1])->count();

        $data['goodcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 1)->count();
        $data['lastgoodcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 1)
            ->where('createtime', '>=', $last_month[0])
            ->where('createtime', '<=', $last_month[1])->count();
        $data['nowgoodcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 1)
            ->where('createtime', '>=', $now_month[0])
            ->where('createtime', '<=', $now_month[1])->count();

        $data['badcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 0)->count();
        $data['lastbadcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 0)
            ->where('createtime', '>=', $last_month[0])
            ->where('createtime', '<=', $last_month[1])->count();
        $data['nowbadcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 0)
            ->where('createtime', '>=', $now_month[0])
            ->where('createtime', '<=', $now_month[1])->count();

        $data['statecount'] = StudentState::where('coach_id', $user->item_id)->count();
        $data['laststatecount'] = StudentState::where('coach_id', $user->item_id)->where('createtime', '>=', $last_month[0])
            ->where('createtime', '<=', $last_month[1])->count();
        $data['nowstatecount'] = StudentState::where('coach_id', $user->item_id)->where('createtime', '>=', $now_month[0])
            ->where('createtime', '<=', $now_month[1])->count();

        return $this->successResponse('success', ['data' => $data]);
    }


    /**
     * @api {get} /coach/searchReport 我的报表搜索
     * @apiDescription 我的报表搜索
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/searchReport
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {String} [starttime]  开始时间
     * @apiParam {String} [endtime]  结束时间
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function searchReport(Request $request)
    {

        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $time_area = [strtotime($request->input('starttime')), strtotime($request->input('endtime') . ' +1 day') - 1];

        $data['stu_count'] = StudentCoach::where('cid', $user->item_id)->count(DB::raw('distinct stuid'));

        $period_count = $this->period->coachPeriodCount($user->item, '', date('Y-m-d', $time_area[0]), date('Y-m-d H:i:s', $time_area[1]));
        $data['putimecount'] = $period_count['puted'];
        $data['completecount'] = $period_count['subscribed'];
        $data['verygoodcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 2)
            ->where('createtime', '>=', $time_area[0])
            ->where('createtime', '<=', $time_area[1])
            ->count();
        $data['goodcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 1)
            ->where('createtime', '>=', $time_area[0])
            ->where('createtime', '<=', $time_area[1])->count();
        $data['badcommentcount'] = Comment::where('coach_id', $user->item_id)->where('comment', 0)
            ->where('createtime', '>=', $time_area[0])
            ->where('createtime', '<=', $time_area[1])->count();
        $data['statecount'] = StudentState::where('coach_id', $user->item_id)
            ->where('createtime', '>=', $time_area[0])
            ->where('createtime', '<=', $time_area[1])->count();

        return $this->successResponse('success', ['data' => $data]);
    }


    /**
     * @api {post} /coach/delPeriod 删除工时排班
     * @apiDescription 删除工时排班
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/delPeriod
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {String} [period_id]  删除的工时ID
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function delPeriod(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $period_id = $request->input('period_id');

        $rs = $this->period->delPeriod($period_id);

        if ($rs['state']) {
            return $this->successResponse('success');
        } else {
            return $this->errorResponse($rs['msg']);
        }
    }


    /**
     * @api {get} /coach/templateList 工时模板列表
     * @apiDescription 工时模板列表
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/templateList
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {String} [date]  获取模板的时间
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function templateList(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $param['coach'] = $user->item;
        $param['times'] = $request->input('date') ? strtotime($request->input('date')) : strtotime(date('Y-m-d'));

        $rs = $this->template->index($param);

        if ($rs) {
            return $this->successResponse('success', ['data' => $rs]);
        } else {
            return $this->errorResponse($rs['msg']);
        }
    }


    /**
     * @api {post} /coach/templateAdd 工时模板添加时段
     * @apiDescription 工时模板添加时段
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/templateAdd
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Int} [max]  最多人数
     * @apiParam {String} [times]  模板日期
     * @apiParam {String} [startime]  开始时间
     * @apiParam {String} [endtime]  结束时间
     * @apiParam {Int} [sum_period]  总学时
     * @apiParam {Int} [km]  科目
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function templateAdd(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $param = $request->input();
        $param['coach_id'] = $user->item_id;
        $param['coach'] = $user->item;
        $param['type'] == 2;
        $param['times'] = $param['times'] ? strtotime($param['times']) : strtotime(date('Y-m-d'));

        $param['minute'] = (strtotime(date('Y-m-d '.$param['endtime'])) - strtotime(date('Y-m-d '.$param['startime']))) / 60;

        $rs = $this->template->store($param);

        if ($rs) {
            return $this->successResponse('success');
        } else {
            return $this->errorResponse($this->template->error);
        }
    }


    /**
     * @api {post} /coach/templateSaveDefault 教练模板设为个人默认
     * @apiDescription 教练模板设为个人默认
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/templateSaveDefault
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {String} [date]  模板日期
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function templateSaveDefault(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $rs = $this->template->templateSaveDefault($user->item, $request->input('date'));

        if ($rs['state']) {
            return $this->successResponse('success');
        } else {
            return $this->errorResponse($rs['msg']);
        }

    }



    /**
     * @api {post} /coach/templateUpate 工时模板修改时段
     * @apiDescription 工时模板修改时段
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/templateUpate
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Int} [id]  修改的模板id
     * @apiParam {Int} [max]  最多人数
     * @apiParam {String} [times]  模板日期
     * @apiParam {String} [startime]  开始时间
     * @apiParam {String} [endtime]  结束时间
     * @apiParam {Int} [type]  个人模板默认1，单日模板2
     * @apiParam {Int} [sum_period]  总学时
     * @apiParam {Int} [km]  科目
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function templateUpate(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $param = $request->input();
        $param['coach_id'] = $user->item_id;
        $param['coach'] = $user->item;

        if($param['type'] == 1){
            $param['times'] = 0;
        }else{
            $param['times'] = $param['times'] ? strtotime($param['times']) : strtotime(date('Y-m-d'));
        }

        $param['minute'] = (strtotime(date('Y-m-d '.$param['endtime'])) - strtotime(date('Y-m-d '.$param['startime']))) / 60;

        $rs = $this->template->update($param['id'], $param);

        if ($rs) {
            return $this->successResponse('success', ['data' => $rs]);
        } else {
            return $this->errorResponse($this->template->error);
        }
    }

    /**
     * @api {get} /coach/templateDel 工时模板删除
     * @apiDescription 工时模板删除
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/templateDel
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Int} [id]  获取模板的时间
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function templateDel(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $rs = $this->template->destroy($request->input('id'));

        if ($rs) {
            return $this->successResponse('success');
        } else {
            return $this->errorResponse('操作失败');
        }
    }


    /**
     * @api {get} /coach/periodPutlist 教练学时投放列表
     * @apiDescription 教练学时投放列表
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/periodPutlist
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {String} [date]  投放的日期
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function periodPutlist(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $rs = $this->period->periodPutlist($user->item, $request->input('date'));

        if ($rs['state']) {
            return $this->successResponse('success', ['data' => $rs['data']]);
        } else {
            return $this->errorResponse($rs['msg']);
        }
    }


    /**
     * @api {post} /coach/periodAdd 教练学时投放
     * @apiDescription 教练学时投放
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/periodAdd
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {String} [template_id]  投放模板id列表，英文逗号分隔的字符串
     * @apiParam {String} [date]  投放的日期
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function periodAdd(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $rs = $this->period->periodAdd($user->item, $request->input());

        if ($rs['state']) {
            return $this->successResponse('success');
        } else {
            return $this->errorResponse($rs['msg']);
        }
    }


    /**
     * @api {get} /coach/studentSublist 教练帮学员预约列表
     * @apiDescription 教练帮学员预约列表
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/studentSublist
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Int} [km]  科目
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function studentSublist(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $coach_config = $user->item->config;

        if($coach_config && !$coach_config->ch_help_putime){
            return $this->errorResponse('没有权限帮学员预约');
        }

        $rs = $this->subscribe->studentSublist($user->item, $request->input('km'));

        if ($rs['state']) {
            return $this->successResponse('success', ['data' => $rs['data']]);
        } else {
            return $this->errorResponse($rs['msg']);
        }
    }


    /**
     * @api {post} /coach/sutdentSub 教练帮学员预约处理
     * @apiDescription 教练帮学员预约处理
     * @apiGroup Coach
     * @apiSampleRequest /api/coach/sutdentSub
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Int} [pid]  学时ID
     * @apiParam {Int} [student_id]  学员id
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": []
     *   }
     */
    public function sutdentSub(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if (!$this->checkCoachToken($user->item, JWTAuth::getToken())) {
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $coach_config = $user->item->config;

        if($coach_config && !$coach_config->ch_help_putime){
            return $this->errorResponse('没有权限帮学员预约');
        }

        $param = [
            'putime_id'=>$request->get('pid'),
            'student_id'=>$request->get('student_id'),
            'user_id'=>$user->id,
            'ispick_up'=>$request->get('is_pickup',0),
        ];

        $status_info = $this->subscribe->store($param);

        if($status_info !== false){

            if($status_info->km == 2){
                $km = '科二实操练习';
            }else{
                $km = '科三实操练习';
            }
            $msg['content'] = $status_info->coach->name.'教练帮您预约了：'.date('Y-m-d H:i', $status_info->startime).' ~ '.date('H:i', $status_info->endtime).' 的'.$km.'，要按时到达哦';
            $msg['from_type'] = 2;//消息来源学员
            $msg['from_id'] = $user->item->id;
            $msg['to_type'] = 1;//消息接受学员
            $msg['to_id'] = $param['student_id'];

            $student_info = Student::find($param['student_id']);
            if($student_info->device_type == 'ios'){
                $msg['device_type'] = 1;
            }elseif($student_info->device_type == 'android'){
                $msg['device_type'] = 2;
            }
            $this->message->store($msg);

            if( $student_info->device_token ){
                $umen = new Umeng($student_info->device_type, 3);
                $umen->sendNotificationToDevices(['title' => '预约提示', 'text' => $msg['content'], 'device_tokens' => $student_info->device_token]);
            }
            //发送给教练
            $msg['content'] = '您帮'.$student_info->name.'学员预约了：'.date('Y-m-d H:i', $status_info->startime).' ~ '.date('H:i', $status_info->endtime).' 的'.$km;
            $msg['from_type'] = 2;//消息来源
            $msg['from_id'] = $user->item->id;;
            $msg['to_type'] = 2;//消息接受教练
            $msg['to_id'] = $status_info->coach->id;
            $msg['device_type'] = 3;
            $this->message->store($msg);

            $coach_id = User::where('item_id',$status_info->coach->id)->where('item_type','App\Models\Coach')->value('id');
            $student_count = StudentCount::where('student_id',$student_info->id)->first();
            $data['km'] = $status_info->km;
            $data['status'] = 1;
            $data['userId'] = $user->id;
            $data['name']  = $student_info->name;
            $data['phone'] = $student_info->phone;
            $data['cocahUserId'] = $coach_id;
            $data['cocahName'] = $status_info->coach->name;
            $data['cocahPhone'] = $status_info->coach->mobile;
            $data['location'] = '';
            $data['use_hours'] = $status_info->study_time;
            $data['surplus_hours'] = $student_count->km2period + $student_count->km3period;
            $data['times'] = date('Y-m-d H:i', $status_info->startime).' ~ '.date('H:i', $status_info->endtime);
            $data['userType'] = 2;
            $this->subscribe->post_weixin_student_yy($data);
            return $this->successResponse('预约成功');
        }else{
            return $this->errorResponse($this->subscribe->error?$this->subscribe->error:'预约失败');
        }
    }
}